﻿#region << 文 件 说 明 >>
/*----------------------------------------------------------------
// 文件名称：LoginViewModel
// 创 建 者：杨程
// 创建时间：2021/9/10 12:35:58
// 文件版本：V1.0.0
// ===============================================================
// 功能描述：
//		
//
//----------------------------------------------------------------*/
#endregion

using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using V.CodeGenerator.CreateCodes.Interface;
using V.CodeGenerator.CreateCodes.Model;
using V.CodeGenerator.Model;
using Vampirewal.Core;
using Vampirewal.Core.Interface;
using Vampirewal.Core.SimpleMVVM;
using Vampirewal.Core.Tools;
using Vampirewal.Core.IoC;
using Vampirewal.Core.WpfTheme.WindowStyle;
using V.CodeGenerator.CreateCodes;

namespace V.CodeGenerator.ViewModel
{
    public class ProjectPoco_View : ProjectPoco
    {

    }

    [VampirewalIoCRegister(ViewModelKey.LoginViewModel, RegisterType.ViewModel)]
    public class LoginViewModel : BillListBaseVM<ProjectPoco, ProjectPoco_View>
    {


        private ILogger Logger;
        private ICreateCode CodeGenerator;

        public LoginViewModel(IAppConfig appConfig, IDialogMessage dialog, ILogger logger, IDataContext dc, ICreateCode createCode) : base(dc, appConfig, dialog)
        {

            Logger = logger;
            CodeGenerator = createCode;

            Title = $"{appConfig.AppChineseName}-{appConfig.AppVersion}";

            SystemDataContext.GetInstance().loginUserInfo = new Vampirewal.Core.Models.LoginUserInfo()
            {
                ITCode="10001",
                Name="admin"
            };

            var aaa = new VCodeGeneratorPro();
            aaa.SetProject(new ProjectPoco());
        }

        public override void InitData()
        {
            
        }

        public override ISugarQueryable<ProjectPoco_View> GetSearchQuery()
        {
            return DC.Client.Queryable<ProjectPoco>().Select<ProjectPoco_View>();
        }

        protected override void InitVM()
        {
            GetList(true);
        }

        protected override FrameworkElement SetView()
        {
            return VampirewalIoC.GetInstance().GetInstance<FrameworkElement>(ViewKey.AddProjectView);
        }

        

        #region 属性

        #endregion

        #region 公共方法

        #endregion

        #region 私有方法

        #endregion

        #region 命令
        /// <summary>
        /// 添加新的工程命令
        /// </summary>
        public RelayCommand AddNewSolutionBtnCommand => new RelayCommand(() =>
        {
            //Messenger.Default.Send("OpenWinodw", "AddProjectView");
            //var NewProject = Messenger.Default.Send<object>("OpenDialogWindowGetResult", ViewKey.AddProjectView);
            //SetDialogWindowSetting(new DialogWindowSetting()
            //{
            //    UiView = VampirewalIoC.GetInstance().GetInstance<FrameworkElement>(ViewKey.AddProjectView),
            //    TitleFontSize = 15,
            //    IsShowMaxButton = false,
            //    IsShowMinButton = false,
            //    IsOpenWindowSize = false,
            //    WindowHeight = 460,
            //    WindowWidth = 425,
            //    IconStr = @"pack://application:,,,/V.CodeGenerator.View;component/Vampirewal-Logo.png"
            //});
            //ExecuteShowDialogWindowCommand(null);

            var NewProject=Dialog.OpenDialogWindow(new DialogWindowSetting()
            {
                UiView= VampirewalIoC.GetInstance().GetInstance<FrameworkElement>( ViewKey.AddProjectView),
                TitleFontSize = 15,
                IsShowMaxButton=false,
                IsShowMinButton=false,
                IsOpenWindowSize=false,
                WindowHeight= 460,
                WindowWidth= 425,
                IconStr= @"pack://application:,,,/V.CodeGenerator.View;component/Vampirewal-Logo.png"
            });

            if (!string.IsNullOrEmpty(((ProjectPoco)NewProject).ProjectName))
            {
                GetList(true);
            }

        });

        /// <summary>
        /// 刷新命令=>重新读取工程信息
        /// </summary>
        public RelayCommand RefreshSolutionViewCommand => new RelayCommand(() =>
        {
            GetList(true);
        });

        /// <summary>
        /// 打开工程命令
        /// </summary>
        public RelayCommand<ProjectPoco> OpenProjectCommand => new RelayCommand<ProjectPoco>((p) =>
        {
            ((Window)View).Hide();
            ((Window)View).ShowInTaskbar = false;

            GetProjectAll(p);

            var result = OpenMainView(p);


            if (result == true)
            {
                ((Window)View).Show();
                ((Window)View).ShowInTaskbar = true;
            }
            else
            {
                ((Window)View).Close();
            }

            
        });

        private bool OpenMainView(ProjectPoco p)
        {
            var mainwindow = VampirewalIoC.GetInstance().GetInstance<Window>(ViewKey.MainView);
            ViewModelBase vm = mainwindow.DataContext as ViewModelBase;
            vm.View = mainwindow;
            vm.PassData(p);

            mainwindow.ShowDialog();
            
            return (bool)vm.GetResult();
        }

        /// <summary>
        /// 删除工程命令
        /// </summary>
        public RelayCommand<ProjectPoco> DeleteProjectCommand => new RelayCommand<ProjectPoco>((p) =>
        {
            if (p != null)
            {

                #region 取数据
                var modulefunctions = DC.Client.Queryable<ModulePoco>().Where(w => w.ProjectId == p.BillId).ToList();
                var models = DC.Client.Queryable<ModelPoco>().Where(w => w.ProjectPocoId == p.BillId).ToList();
                var modelDtls = new List<ModelDtlPoco>();
                foreach (var item in models)
                {
                    var modelDtl = DC.Client.Queryable<ModelDtlPoco>().Where(w => w.ModelPocoId == item.BillId).ToList();
                    modelDtls.AddRange(modelDtl);
                }

                var views = DC.Client.Queryable<ViewPoco>().Where(w => w.ProjectPocoId == p.BillId).ToList();
                var controls = new List<ControlPoco>();
                foreach (var item in views)
                {
                    var control = DC.Client.Queryable<ControlPoco>().Where(w => w.ViewPocoId == item.BillId).ToList();
                    controls.AddRange(control);
                }
                #endregion

                #region 执行删除操作

                try
                {
                    DC.Client.BeginTran();

                    DC.DeleteEntityList(modulefunctions);
                    DC.DeleteEntityList(models);
                    DC.DeleteEntityList(modelDtls);
                    DC.DeleteEntityList(views);
                    DC.DeleteEntityList(controls);
                    DC.DeleteEntity(p);

                    DC.Client.CommitTran();
                }
                catch (Exception e)
                {
                    DC.Client.RollbackTran();
                }
                finally
                {
                    GetList(true);
                }
                #endregion
                
            }
        });

        /// <summary>
        /// 一键输出整个项目命令
        /// </summary>
        public RelayCommand<ProjectPoco> AKeyOutputSolutionCommand => new RelayCommand<ProjectPoco>((p) =>
        {
            Task.Run(() =>
            {
                #region new
                //CodeGenerator.SetSavePath($"{p.SaveFolderPath}\\{p.ProjectName}");

                //CodeGenerator.SetBaseInfo()
                #endregion

                CreateCodes.CreateCodes.NameSpace = p.ProjectName;
                CreateCodes.CreateCodes.SetSavePath($"{p.SaveFolderPath}\\{p.ProjectName}");//将保存地址传递过去

                var details = DC.Client.Queryable<ProjectModelDtl>().Where(w => w.BillId == p.BillId && w.IsDetail == true).ToList();



                foreach (var item in details)
                {
                    var model = new CreateCodes.Model.ModelPoco()
                    {
                        ClassName = item.DtlName,
                        DisplayName = item.DisplayName,
                        TableName = $"{item.DtlName}s",
                        InheritanceBaseModel = item.Inheritance
                    };

                    var current = DC.Client.Queryable<ModelEdit>().Where(w => w.ProjectModelDtlId == item.DtlId).ToList();

                    foreach (var modeledit in current)
                    {
                        var modeldtl = new CreateCodes.Model.ModelDtlPoco()
                        {
                            PropName = modeledit.PropName,
                            PropDes = modeledit.PropDes,
                            propType = modeledit.propType.ToString(),
                            PropLength = modeledit.PropLength,
                            PropPrecision = modeledit.PropPrecision,
                            MinValue = modeledit.MinValue,
                            MaxValue = modeledit.MaxValue,
                            IsCreateDbProp = modeledit.IsCreateDbProp,
                            IsRequired = modeledit.IsRequired
                        };

                        //model.ModelPropPocos.Add(modeldtl);

                        model.AddProp(modeldtl);
                    }

                    CreateCodes.CreateCodes.ModelPocos.Add(model);

                }

                CreateCodes.CreateCodes.Build(true, (e) =>
                {
                    Dialog.ShowPopupWindow($"生成失败！{e}", (Window)View, MessageType.Error);
                    return;
                });

                UIInvoke(new Action(() =>
                {
                    Dialog.ShowPopupWindow("生成成功！", (Window)View, MessageType.Successful);
                }));
            });
        });
        #endregion

        /// <summary>
        /// 获取工程全部信息
        /// </summary>
        /// <param name="project"></param>
        private void GetProjectAll(ProjectPoco project)
        {
            //获取ModuleFunction
            var modulefunctions = DC.Client.Queryable<ModulePoco>().Where(w => w.ProjectId == project.BillId).ToList();

            //获取modelPoco
            var modelpocos = DC.Client.Queryable<ModelPoco>().Where(w => w.ProjectPocoId == project.BillId).ToList();
            foreach (var item in modelpocos)
            {
                //获取model字段属性
                var modeldtl = DC.Client.Queryable<ModelDtlPoco>().Where(w => w.ModelPocoId == item.BillId).ToList();
                item.GetModelDtl(modeldtl);
            }

            //获取View
            var viewpocos = DC.Client.Queryable<ViewPoco>().Where(w => w.ProjectPocoId == project.BillId).ToList();
            foreach (var item in viewpocos)
            {
                //获取View中控件属性
                var control = DC.Client.Queryable<ControlPoco>().Where(w => w.ViewPocoId == item.BillId).ToList();
                item.GetControls(control);
            }



            project.GetModuleFunction(modulefunctions)
                   //.BuildModuleFunctionTree(Guid.Empty.ToString())
                   .GetModelPoco(modelpocos)
                   .GetViewPoco(viewpocos);
        }


    }
}
